package com.chuji.crmcj.act;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.chuji.crmcj.R;
import com.chuji.crmcj.bean.TryDriveInfo;
import com.chuji.crmcj.utils.UIUtils;
import com.chuji.crmcj.utils.UrlUtils;
import com.chuji.crmcj.utils.VolleyUtil;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

public class TryDriveDetailActivity extends Activity implements View.OnClickListener{
    //返回
    private ImageView mIv_Back;
    /*历史试驾信息显示*/
    private ListView lv_try_drive_history;
    /*试乘试驾信息存储*/
    List<TryDriveInfo.ApiParamObjEntity> tryDriveData;
    /*试乘试驾信息网络数据*/
    private TryDriveInfo tryDriveInfo;
    //试驾类型
    private LinearLayout mLl_try_drive_type;
    private TextView mTv_try_drive_type;
    private String type;
    //试驾配置
    private LinearLayout mLl_try_drive_configure;
    private TextView mTv_try_drive_configure;
    private String configure;
    //试驾表现
    private LinearLayout mLl_try_drive_expression;
    //历史试驾信息显示
    private LinearLayout ll_try_drive_history;
    private TextView mTv_try_drive_expression;
    private String expression;
    //补充说明
    private EditText mEt_relenish_explain;
    //意图
    private Intent mIntent;
    //请求码
    private int requestCode;
    //适配器
    CustomTryDriveHistoryAdapter customTryDriveHistoryAdapter;
    //客流ID
    private String FlowID;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_try_drive_detail);
        //初始化组件
        mIv_Back = (ImageView) findViewById(R.id.iv_Back);
        lv_try_drive_history= (ListView) findViewById(R.id.lv_try_drive_history);
        mLl_try_drive_type = (LinearLayout) findViewById(R.id.ll_try_drive_type);
        mTv_try_drive_type = (TextView) findViewById(R.id.tv_try_drive_type);
        mLl_try_drive_configure = (LinearLayout) findViewById(R.id.ll_try_drive_configure);
        mTv_try_drive_configure = (TextView) findViewById(R.id.tv_try_drive_configure);
        mLl_try_drive_expression = (LinearLayout) findViewById(R.id.ll_try_drive_expression);
        mTv_try_drive_expression = (TextView) findViewById(R.id.tv_try_drive_expression);
        mEt_relenish_explain = (EditText) findViewById(R.id.et_relenish_explain);
        ll_try_drive_history= (LinearLayout) findViewById(R.id.ll_try_drive_history);
        //初始化数据
        initData();
        //初始化适配器
        customTryDriveHistoryAdapter=new CustomTryDriveHistoryAdapter();
        //填充
        lv_try_drive_history.setAdapter(customTryDriveHistoryAdapter);
        //设置点击事件
        mIv_Back.setOnClickListener(this);
        mLl_try_drive_type.setOnClickListener(this);
        mLl_try_drive_configure.setOnClickListener(this);
        mLl_try_drive_expression.setOnClickListener(this);
    }
    private void initData() {
        /**
         * 获得试驾信息
         */
        getTryDriveData();
    }

    private void getTryDriveData() {
        //第一次
        if (tryDriveData == null) {
            tryDriveData = new ArrayList<TryDriveInfo.ApiParamObjEntity>();
        }
        requestStandData();
    }
    private void requestStandData() {
        //初始化Volley
        String strURL = String.format(UrlUtils.TRY_DRIVE_SHOW+"&CustomerID="+"2D5640C9-EB6B-4A2B-9147-581B3D059A86");
        StringRequest stringRequest = new StringRequest(Request.Method.GET, strURL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                tryDriveInfo = JSON.parseObject(response, TryDriveInfo.class);
                tryDriveData.addAll(tryDriveInfo.getApiParamObj());
                UIUtils.runInMainThread(new Runnable() {
                    @Override
                    public void run() {
                        if(tryDriveInfo.getCount()==0){
                            ll_try_drive_history.setVisibility(View.GONE);
                        }else{
                            ll_try_drive_history.setVisibility(View.VISIBLE);
                        }
                        // 判断adapter是否创建
                        if (customTryDriveHistoryAdapter == null) {
                            customTryDriveHistoryAdapter = new CustomTryDriveHistoryAdapter();
                            lv_try_drive_history.setAdapter(customTryDriveHistoryAdapter);
                        } else {
                            customTryDriveHistoryAdapter.notifyDataSetChanged();
                        }
                    }
                });
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
                System.out.println("失败" + error);
                UIUtils.showToastSafe("请检查网络");
            }
        });
        // Add the request to the RequestQueue.
        VolleyUtil.getRequestQueue().add(stringRequest);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //试驾车型返回数据
         type = data.getStringExtra("type");
        //试驾配置返回数据
         configure = data.getStringExtra("configure");
        //试驾表现返回数据
         expression = data.getStringExtra("expression");
        // 根据上面发送过去的请求码来区别
        switch (requestCode) {
            case 0:
                mTv_try_drive_type.setText(type);
                break;
            case 1:
                if(configure.equals("")){
                    mTv_try_drive_configure.setText("未填写");
                }else {
                    mTv_try_drive_configure.setText(configure);
                }
                break;
            case 2:
                if(expression.equals(" ")){
                    mTv_try_drive_expression.setText("未填写");
                }else {
                    mTv_try_drive_expression.setText(expression);
                }
                break;
            default:
                break;
        }
    }
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_Back:
                //保存试驾表现信息
                //将用户输入的信息上传到服务器
                new Thread() {
                    public void run() {
                        //获取用户输入
                        String Content=mEt_relenish_explain.getText().toString();
                        //获取用户UserId
//                        FlowID = SPUtils.getString(TryDriveDetailActivity.this, "FlowID", "");
                        FlowID="F248611C-CB39-4806-919E-71DCD085D208";
                        RequestParams params = new RequestParams(UrlUtils.SUBMIT_CLEINT_TRY_DRIVE_INFO);
                        // 加到url里的参数, http://xxxx/s?wd=xUtils
                        params.addQueryStringParameter("FlowID",FlowID);
                        params.addQueryStringParameter("CarModel",type);
                        params.addQueryStringParameter("CarConfiguration",configure);
                        params.addQueryStringParameter("Presentation",expression);
                        params.addQueryStringParameter("Content",Content);
                        // 添加到请求body体的参数, 只有POST, PUT, PATCH, DELETE请求支持.
                        // params.addBodyParameter("wd", "xUtils");
                        x.http().post(params, new Callback.CommonCallback<String>() {
                            @Override
                            public void onSuccess(String result) {
                                UIUtils.showToastSafe("提交用户成功");
                            }
                            @Override
                            public void onError(Throwable ex, boolean isOnCallback) {
                                Toast.makeText(x.app(), ex.getMessage(), Toast.LENGTH_LONG).show();
                            }

                            @Override
                            public void onCancelled(CancelledException cex) {
                                Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
                            }

                            @Override
                            public void onFinished() {

                            }
                        });
                    }
                }.start();
                finish();
                break;
            case R.id.ll_try_drive_type:
                //跳转到选择车型界面
                mIntent = new Intent();
                mIntent.setClass(UIUtils.getContext(), TurnoverTypeActivity.class);
                // 请求码的值随便设置，但必须>=0
                requestCode = 0;
                startActivityForResult(mIntent, requestCode);
                break;
            case R.id.ll_try_drive_configure:
                //跳转到配置选择配置界面
                mIntent = new Intent();
                mIntent.setClass(UIUtils.getContext(), CarConfigureActivity.class);
                // 请求码的值随便设置，但必须>=0
                requestCode = 1;
                startActivityForResult(mIntent, requestCode);
                break;
            case R.id.ll_try_drive_expression:
                //跳转到试驾表现选择界面
                mIntent = new Intent();
                mIntent.setClass(UIUtils.getContext(), TryDriveExpressionActivity.class);
                // 请求码的值随便设置，但必须>=0
                requestCode = 2;
                startActivityForResult(mIntent, requestCode);
                break;
            default:
                break;
        }
    }
    class CustomTryDriveHistoryAdapter extends BaseAdapter {

        private Context context;

        @Override
        public int getCount() {
            return tryDriveData.size();
        }

        @Override
        public Object getItem(int i) {
            return tryDriveData.get(i);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup viewGroup) {
            /****1)根据list_item.xml--》得到当前子项元素的布局   【界面】*******/
            //b)声明ViewHolder
            ViewHolder viewHolder = null;
            //c)判断convertView是否为null
            if (convertView == null) {//第一次调用getView（）方法时为 null,意思就是在内存中没有
                viewHolder = new ViewHolder();
                convertView =  LayoutInflater.from(UIUtils.getContext()).inflate(R.layout.listview_try_drive_history, null);
                //初始化组件
                viewHolder.tv_car_type = (TextView) convertView.findViewById(R.id.tv_car_type);
                viewHolder.tv_drive_configure = (TextView) convertView.findViewById(R.id.tv_drive_configure);
                viewHolder.tv_drive_expression = (TextView) convertView.findViewById(R.id.tv_drive_expression);
                viewHolder.tv_relenish_explain = (TextView) convertView.findViewById(R.id.tv_relenish_explain);
                viewHolder.tv_drive_time = (TextView) convertView.findViewById(R.id.tv_drive_time);
//                viewHolder.iv_apply_tag = (ImageView) convertView.findViewById(R.id.iv_apply_tag);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            viewHolder.tv_car_type.setText(tryDriveData.get(position).getCarModel());
            viewHolder.tv_drive_configure.setText("奔驰");
            viewHolder.tv_drive_expression.setText(tryDriveData.get(position).getPresentation());
            viewHolder.tv_relenish_explain.setText(tryDriveData.get(position).getComment());
            viewHolder.tv_drive_time.setText(tryDriveData.get(position).getCreateTime());
//            if(loseApproveData.get(position).getState()==0){
//                viewHolder.iv_apply_tag.setVisibility(View.VISIBLE);
//            }else {
//                viewHolder.iv_apply_tag.setVisibility(View.GONE);
//            }
            return convertView;
        }
    }
    static class ViewHolder {
        private TextView tv_car_type;
        private TextView tv_drive_configure;
        private TextView tv_drive_expression;
        private TextView tv_relenish_explain;
        private TextView tv_drive_time;
    }
}
